package com.ruoyi.system.util;

/**
 * Created with IntelliJ IDEA.
 *
 * @author: 风离
 * @Date: 2022/04/11/20:55
 * @Description:
 */

import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Calendar;
import java.util.Locale;
import java.util.TimeZone;

/**
 * Created with IntelliJ IDEA.
 *
 * @author: 风离
 * @Date: 2021/09/22/21:05
 * @Description:
 */
@Data
@Getter
@Setter
@ToString
public class UpFileUtils {
    private static final String HMAC_SHA1_ALGORITHM = "HmacSHA1";
    private final static String host = "http://v0.api.upyun.com";

    private static String operator = "manouchaowan";
    private static String secret = "fhlLSXywTqntAtt2qFFgx7SHuRnEfPHG";


    private final static String method = "PUT";
    private final static String uri = "/manouchaowan/file/";

    private  String date = getRfc1123Time();


    public int up(File img,String fileName) throws Exception{
        String newUrl = uri+fileName;
        URL url =new URL(host+newUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod(method);
        conn.setUseCaches(false);
        conn.setDoOutput(true);
        conn.setRequestProperty("Authorization",getAuth(newUrl));
        conn.setRequestProperty("date",date);
        //创建连接
        conn.connect();
        InputStream inputStream = new FileInputStream(img);
        OutputStream os =conn.getOutputStream();
        byte[] data = new byte[4096];
        int temp = 0;

        // 上传文件内容
        while ((temp = inputStream.read(data)) != -1) {
            os.write(data, 0, temp);
        }

        /**
         * //返回的状态码
         */
        int responseCode = conn.getResponseCode();

        if (os != null) {
            os.close();
            os = null;
        }
        if (inputStream != null) {
            inputStream.close();
            inputStream = null;
        }
        if (conn != null) {
            conn.disconnect();
            conn = null;
        }
        System.out.println(responseCode);


        return responseCode;
    }


    /**
     * 获取签名
     * @return 签名
     */
    private  String getAuth(String newUrl) throws Exception {
        return sign(operator, md5(secret), method, newUrl, date, "", "");
    }

    private  String md5(String string) {
        byte[] hash;
        try {
            hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("UTF-8 is unsupported", e);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("MessageDigest不支持MD5Util", e);
        }
        StringBuilder hex = new StringBuilder(hash.length * 2);
        for (byte b : hash) {
            if ((b & 0xFF) < 0x10)
            {
                hex.append("0");
            }
            hex.append(Integer.toHexString(b & 0xFF));
        }
        return hex.toString();
    }
    private  byte[] hashHmac(String data, String key)
            throws SignatureException, NoSuchAlgorithmException, InvalidKeyException {
        SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), HMAC_SHA1_ALGORITHM);
        Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
        mac.init(signingKey);
        return mac.doFinal(data.getBytes());
    }
    public String sign(String key, String secret, String method, String uri, String date, String policy,
                              String md5) throws Exception {
        String value = method + "&" + uri + "&" + date;
        if (policy != "") {
            value = value + "&" + policy;
        }
        if (md5 != "") {
            value = value + "&" + md5;
        }
        byte[] hmac = hashHmac(value, secret);
        System.out.println(value);
        String sign = Base64.getEncoder().encodeToString(hmac);
        return "UPYUN " + key + ":" + sign;
    }
    public  String getRfc1123Time() {
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                "EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
        dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
        return dateFormat.format(calendar.getTime());
    }

}
